package com.kfm.base.date;

import java.util.Random;

public class Exer01 {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            String pass = rand(9);
            System.out.println(pass);
        }
    }

    public static String rand(int length) {
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String[] charArray = characters.split("");

        Random rand = new Random();
        // 第一个是字母
        int index = rand.nextInt(52);
        StringBuilder sb = new StringBuilder(charArray[index]);

        boolean hasNum = false; // 是否有数字
        for (int i = 1; i < length; ) {
            // 随机字符下标
            index = rand.nextInt(charArray.length);
            // 判断在字符串中有没有
            if (sb.indexOf(charArray[index]) == -1) {
                if (index >= 52 && index < charArray.length - 1){
                    hasNum = true;
                }
                sb.append(charArray[index]);
                i++;
            }
        }

        String reg = "^[a-zA-Z]+\\d+\\w*$";
        String str = sb.toString();

        if (!hasNum){
            // 说明没数字
            int num = rand.nextInt(10);
            int repIndex = rand.nextInt(length - 1) + 1;
            str = str.replaceFirst(str.charAt(repIndex) + "", String.valueOf(num));
        }
        return str;
    }
}
